﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ConsumerClient.ServiceReference1;
using System.ServiceModel;

namespace ConsumerClient
{
    /// <summary>
    /// Interaction logic for NewReservation.xaml
    /// </summary>
    public partial class NewReservation : Window
    {
        PlanRouteServiceClient client;
        public WCFUser User { get; set; }

        private List<WCFStation> StationsSorted;
        private WCFStation[] StationsOnRoute;
        private DateTime Date;
        private WCFStation Start;
        private WCFStation Destination;
        private WCFCar Car;

        public NewReservation(WCFUser user, PlanRouteServiceClient client)
        {
            User = user;
            this.client = client;
            InitializeComponent();
            SetDropdownData();
            dpi_date.SelectedDate = DateTime.Today;
            dpi_date.BlackoutDates.AddDatesInPast();
            dpi_date.Width = 102;
        }

        private async void SetDropdownData()
        {
            Task<WCFStation[]> getList = client.GetAllStationsAsync();

            WCFStation[] stationArray = await getList;
            StationsSorted = stationArray.ToList();

            StationsSorted.Sort(delegate(WCFStation s1, WCFStation s2) {
                return s1.City.CompareTo(s2.City); 
            });
            
            foreach (WCFStation s in StationsSorted)
            {
                drd_start.Items.Add(s.Id + ":" + UppercaseFirst(s.City));
                drd_destination.Items.Add(s.Id + ":" + UppercaseFirst(s.City));
            }

            foreach (WCFCar c in User.Cars)
	
            {
                drd_vehicle.Items.Add(c.CarModel.Description + " - " + c.RegistrationNo);  
            }
            // Automatic sets the selected item in vehicle dropdown to the first car in the list.
            drd_vehicle.SelectedIndex = 0;
        }

        private string UppercaseFirst(string s)
        {
            char[] a = s.ToLower().ToCharArray();
            a[0] = char.ToUpper(a[0]);
            return new string(a);
        }


        private async void btn_confirm_Click(object sender, RoutedEventArgs e)
        {
            Task<WCFReservation> getReservation = client.ConfirmRouteAsync(User, Car, StationsOnRoute, Date);
            this.Hide();
            WCFReservation res = await getReservation;
            MessageBox.Show("Din reservation er nu oprettet.");
            this.Close();
        }

        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private async void btn_planRoute_Click(object sender, RoutedEventArgs e)
        {
            // Retrieving inputs from dropdowns in GUI
            btn_planRoute.IsEnabled = false;
            GetDropdownData();
            
            WCFCarModel carModel = Car.CarModel;
            
            // Calling planRoute method in service. Returns a list of staions on the route.
            Task<WCFStation[]> getStationsOnRoute = client.PlanRouteAsync(Start, Destination, Date, carModel);
            bool fault = false;
            try
            {
                StationsOnRoute = await getStationsOnRoute;
            }
            catch (FaultException fe)
            {
                if (fe.Message == "Route not complete!")
                {
                    MessageBox.Show("Kan ikke beregne rute");
                    fault = true;
                }
            }
            // Sets text in GUI
            btn_planRoute.IsEnabled = true;

            // Dummy code to check for 'inf' route.
            if (!fault)
            {
                string subText = "Der er beregnet en route fra " +
                    UppercaseFirst(StationsOnRoute.First().City) +
                    " til " +
                    UppercaseFirst(StationsOnRoute.Last().City) + 
                    ".\nDen totale afstand er beregnet til: "  + StationsOnRoute.Last().Distance + 
                    "km.\n\nDer vil blive reserveret batteri på følgende stationer:\n";
                // Adds information of stations to the subText.
                bool first = true;
                foreach (WCFStation s in StationsOnRoute)
                {
                    if (first) 
                    {
                        subText += UppercaseFirst(s.City);
                        first = false;
                    }
                    else 
                    {
                        subText += ", " + UppercaseFirst(s.City);
                    }
                    
                }
                subText += "\n\nTryk \"Opret reservation\" for at gennemføre reservationen";
                txt_information.Text = subText;
                btn_confirm.IsEnabled = true;
            }            
        }

        private void GetDropdownData()
        {
            Start = StationsSorted[drd_start.SelectedIndex];
            Destination = StationsSorted[drd_destination.SelectedIndex];
            Date = dpi_date.SelectedDate.Value;
            Car = User.Cars[drd_vehicle.SelectedIndex];
        }
    }
}
